<template>
  <el-card>
    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search" v-if="userId === 1">
      <el-form-item>
        <el-button type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table
        :header-cell-style="thStyleFun"
        :cell-style="cellStyleFun"
        height="730px"
        ref="multipleTable"
        :data="tableData"
        border
        tooltip-effect="dark"
        @selection-change="handleSelectionChange"
        style="width: 100%">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          v-for="(index,key) of colData"
          :key="key"
          :prop="index.prop"
          :label="index.label">
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch
              @change="changeUserStatus(scope.row)"
              v-model="scope.row.active"
              inactive-color="#999"
              active-color="#13ce66">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button
              v-if="userId === 1"
              type="danger"
              size="mini"
              @click="handleResetPwd(scope.$index, scope.row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        class="page-box"
        :page-count="pageInfo.totalPage"
        :current-page="pageInfo.pageNo"
        :page-size="pageInfo.pageSize"
        :total="pageInfo.totalNum"
        @size-change="handleSizeChange"
        @current-change="onSelectPageHandler"
        :page-sizes="pageInfo.pageSizeArr"
        layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 编辑界面 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog'>
      <el-form label-width="80px" ref="editForm" :model="editForm" :rules="rules">
        <el-form-item label="工号" prop="account">
          <el-input v-model="editForm.account" readonly auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" auto-complete="off" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-select v-model="editForm.position" placeholder="请选择" class="userRole">
            <el-option label="财务" value="财务"></el-option>
            <el-option label="出纳" value="出纳"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click='closeDialog("edit")'>取消</el-button>
        <el-button type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<style lang="scss" scoped>
  .page-box {
    margin: 10px auto;
  }
  .userRole {
    width: 100%;
  }
</style>

<script>
import {getList, userSave, editUserStatus, resetPwd, getJobNumber} from '@/api/user';
import { getToken } from "@/utils/auth";
import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        multipleSelection: [],
        title: '添加用户',
        loading: false,
        editFormVisible: false, //控制编辑页面显示与隐藏
        editForm: {
          userId: '',
          account: '',
          name: '',
          mobile: '',
          position: '',
          token: getToken
        },
        rules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]{9}$/,
              required: true,
              message: '请输入正确的手机号',
              trigger: 'blur'
            }
          ],
          position: [
            { required: true, message: '请选择角色', trigger: 'blur' }
          ],
        },
        colData: [
         {
            prop: 'account',
            label: '账号',
            width: '120'
          },{
            prop: 'name',
            label: '姓名',
            width: '120'
          },{
            prop: 'position',
            label: '职位',
            width: '120'
          },{
            prop: 'mobile',
            label: '手机',
            width: '120'
          }],
        tableData: [],
        pageInfo: {
          pageNo: 1, // 当前页数
          pageSize: 10, // 当前每页显示多少条
          pageSizeArr: [10, 20, 30, 40],
          totalNum: 12, // 总数
          totalPage: 1
        }
      }
    },
    computed: {
      ...mapGetters([
        'userId'
      ])
    },
    methods: {
      thStyleFun() {
        return 'text-align:center'
      },
      cellStyleFun() {
        return 'text-align:center'
      },
      // 初始化数据
      searchUserListByPage(pageNo, pageSize) {
        const pageInfo = {
          currentPage: pageNo,
          rows: pageSize
        }
        getList.post(pageInfo).then(res  => {
          this.tableData.splice(0, this.tableData.length);
          if (res && res.code == 1000) {
            let data = res.data;
            data.records.map(item => {
              this.tableData.push(item);
            });
            let dataPageInfo = {
              pageNo: data.current,
              pageSize: data.size,
              totalNum: data.total,
              totalPage: data.pages
            };
            Object.assign(this.pageInfo, dataPageInfo);
            this.pageInfo.pageNo = pageNo;
          }
        });
      },
      // 添加用户
      handleEdit(index, row){
        this.editFormVisible = true;
        if (row != undefined && row != 'undefined') {
          this.title = '修改用户';
          this.editForm = {
            userId: row.userId,
            account: row.account,
            name: row.name,
            mobile: row.mobile,
            position: row.position
          };
        } else {
          this.title = '添加用户';
          this.getUserJobNumber();
          this.editForm = {
            account: this.editForm.account,
            userId: "",
            name: "",
            mobile: "",
            position: ""
          };
          window.console.log(this.editForm,"this.editForm")
        }
      },
      // 获取工号
      getUserJobNumber(){
        getJobNumber.get().then(res => {
          this.editForm.account = res.data;
        })
      },
      handleResetPwd(index, row){
        this.$confirm('此操作将会把支付密码初始化，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          resetPwd.post({userId : row.userId}).then(res => {
            if(res.code == 1000) {
              this.$message.success('初始化成功!');
            }
          });
        }).catch(() => {});
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 监听 pageSize 每页显示多少条
      handleSizeChange(val) {
        this.pageInfo.pageSize = val;
        this.searchUserListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize);
      },
      // 监听 页码值 改变事件
      onSelectPageHandler(index){
        this.searchUserListByPage(index, this.pageInfo.pageSize);
      },
      // 关闭编辑、增加弹出框
      closeDialog() {
        this.editFormVisible = false
      },
      // 编辑、添加提交方法
      submitForm(editData) {
        this.$refs[editData].validate(valid => {
          if (valid) {
            // 请求方法
            userSave.post(this.editForm).then(res => {
              this.editFormVisible = false;
              this.loading = false;
              if(res.code == 1000) {
                let msg = this.editForm.userId ? "数据修改成功!" : "数据保存成功!"
                this.$message({
                  type: 'success',
                  message: msg
                })
                this.searchUserListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize);
              }
            });
          } else {
            return false
          }
        })
      },
      // 改变用户状态
      changeUserStatus(user){
        const data = {userId : user.userId, active: user.active};
        editUserStatus.post(data).then(res => {
          if(res.code == 1000) {
            this.$message({
              type: 'success',
              message: '状态修改成功！'
            })
            this.searchUserListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize);
          }
        });
      }
    },
    created() {
      this.searchUserListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize);
    }
  }
</script>